#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

#define N 2
#define NUM 1024

using namespace std;

void Writer(int wfd)
{
    string s = "hello, I am a child!";
    pid_t self = getpid();
    int number = 0;
    char buffer[NUM];
    while(true)
    {
        sleep(1);
        // 构建发送字符串
        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number++);
        // cout << buffer << endl;
        write(wfd, buffer, strlen(buffer));
        // if(number >= 5)
        // {
        //     break;
        // }
    }
}
void Reader(int rfd)
{
    char buffer[NUM];
    int cnt = 0;
    while(true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "father get a message[" << getpid() << "]# " << buffer << endl;
        }
        else if(n == 0)
        {
            printf("father read file done!\n");
            break;
        }
        else
        {
            break;
        }
        cnt++;
        if(cnt > 5)
        {
            break;
        }
    }
}
int main()
{
    int pipefd[N] = { 0 }; 
    int n = pipe(pipefd); // 创建管道
    if(n < 0)
    {
        return 1;
    }
    // 创建子进程
    pid_t id = fork();
    // 判断是否成功
    if(id < 0)
    {
        return 2;
    }
    // 子进程执行任务
    if(id == 0)
    {
        close(pipefd[0]);
        Writer(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    // 父进程执行任务
    close(pipefd[1]);
    Reader(pipefd[0]);
    close(pipefd[0]);
    cout << "father close read fd: " << pipefd[0] << endl;
    sleep(5);
    int status = 0;
    pid_t rid = waitpid(id, &status, 0); // 等待子进程
    if(rid < 0)
    {
        return 3;
    }
    cout << "wait child success: " << rid << " exit code: " << ((status>>8)&0xFF) << " exit signal: " << (status&0x7F) << endl;
    sleep(5);
    cout << "father quit" <<endl;
    // close(pipefd[0]);
    // sleep(5);

    return 0;
}